export const presetTemplates = [
  {
    id: 'vue-crud',
    name: 'Vue CRUD 组件',
    description: '生成一个包含增删改查功能的 Vue 组件',
    variables: [
      {
        key: 'entityName',
        label: '实体名称',
        type: 'text'
      },
      {
        key: 'apiPrefix',
        label: 'API 前缀',
        type: 'text'
      },
      {
        key: 'enableSearch',
        label: '启用搜索',
        type: 'text'
      },
      {
        key: 'tableFields',
        label: '表格字段',
        type: 'array',
        fields: [
          {
            key: 'prop',
            label: '字段名'
          },
          {
            key: 'label',
            label: '显示名称'
          },
          {
            key: 'searchable',
            label: '是否可搜索'
          }
        ]
      }
    ],
    subTemplates: [
      {
        filename: '{{$entityName}}/index.vue',
        content: `<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{$entityName}}管理</span>
          {{#if $enableSearch === 'true'}}
          <div class="search-container">
            {{#each $tableFields}}
              {{#if $item.searchable === 'true'}}
              <el-input
                v-model="queryParams.{{$prop}}"
                placeholder="请输入{{$label}}"
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
              {{/if}}
            {{/each}}
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </div>
          {{/if}}
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
      </template>
      
      <el-table :data="tableData" v-loading="loading" style="width: 100%">
        {{#each $tableFields}}
        <el-table-column prop="{{$prop}}" label="{{$label}}" />
        {{/each}}
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        @current-change="handleQuery"
      />
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
    >
      <el-form ref="formRef" :model="form" label-width="100px">
        {{#each $tableFields}}
        <el-form-item label="{{$label}}" prop="{{$prop}}">
          <el-input v-model="form.{{$prop}}" placeholder="请输入{{$label}}" />
        </el-form-item>
        {{/each}}
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { list{{$entityName}}, get{{$entityName}}, add{{$entityName}}, update{{$entityName}}, delete{{$entityName}} } from '@/api/{{$entityName}}'

const loading = ref(false)
const total = ref(0)
const tableData = ref([])
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  {{#if $enableSearch === 'true'}}
  {{#each $tableFields}}
  {{#if $item.searchable === 'true'}}
  {{$prop}}: '',
  {{/if}}
  {{/each}}
  {{/if}}
})

// 对话框相关
const dialog = reactive({
  visible: false,
  title: '',
  type: 'add'
})

const formRef = ref()
const form = reactive({
  {{#each $tableFields}}
  {{$prop}}: '',
  {{/each}}
})

// 查询列表
const handleQuery = async () => {
  loading.value = true
  try {
    const res = await list{{$entityName}}(queryParams)
    tableData.value = res.rows
    total.value = res.total
  } finally {
    loading.value = false
  }
}

{{#if $enableSearch === 'true'}}
// 重置查询
const resetQuery = () => {
  {{#each $tableFields}}
  {{#if $item.searchable === 'true'}}
  queryParams.{{$prop}} = ''
  {{/if}}
  {{/each}}
  handleQuery()
}
{{/if}}

// 新增
const handleAdd = () => {
  dialog.type = 'add'
  dialog.title = '新增{{$entityName}}'
  dialog.visible = true
  Object.keys(form).forEach(key => form[key] = '')
}

// 编辑
const handleEdit = async (row) => {
  dialog.type = 'edit'
  dialog.title = '编辑{{$entityName}}'
  dialog.visible = true
  const res = await get{{$entityName}}(row.id)
  Object.assign(form, res.data)
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该条数据吗？').then(async () => {
    await delete{{$entityName}}(row.id)
    ElMessage.success('删除成功')
    handleQuery()
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  
  if (dialog.type === 'add') {
    await add{{$entityName}}(form)
    ElMessage.success('新增成功')
  } else {
    await update{{$entityName}}(form)
    ElMessage.success('修改成功')
  }
  
  dialog.visible = false
  handleQuery()
}

handleQuery()
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  {{#if $enableSearch === 'true'}}
  .search-container {
    display: flex;
    gap: 10px;
    align-items: center;
  }
  {{/if}}
}
</style>`
      },
      {
        filename: '{{$entityName}}/api.js',
        content: `import request from '@/utils/request'

// 查询{{$entityName}}列表
export function list{{$entityName}}(query) {
  return request({
    url: '{{$apiPrefix}}/list',
    method: 'get',
    params: query
  })
}

// 查询{{$entityName}}详细
export function get{{$entityName}}(id) {
  return request({
    url: '{{$apiPrefix}}/' + id,
    method: 'get'
  })
}

// 新增{{$entityName}}
export function add{{$entityName}}(data) {
  return request({
    url: '{{$apiPrefix}}',
    method: 'post',
    data: data
  })
}

// 修改{{$entityName}}
export function update{{$entityName}}(data) {
  return request({
    url: '{{$apiPrefix}}',
    method: 'put',
    data: data
  })
}

// 删除{{$entityName}}
export function delete{{$entityName}}(id) {
  return request({
    url: '{{$apiPrefix}}/' + id,
    method: 'delete'
  })
}`
      }
    ]
  },
  {
    id: 'vue-tab',
    name: 'Tab页面',
    description: '生成Tab页面',
    variables: [
      {
        key: 'folderName',
        label: '文件夹名称',
        type: 'text'
      },
      {
        key: 'pageName',
        label: '页面名称',
        type: 'text'
      },
      {
        key: 'tabFields',
        label: 'Tab子页',
        type: 'array',
        fields: [
          {
            key: 'key',
            label: 'Tab页Code'
          },
          {
            key: 'label',
            label: 'Tab页名称'
          }
        ]
      },
      {
        key: 'showTab',
        label: '默认显示Tab页Code',
        type: 'text'
      }
    ],
    subTemplates: [
      {
        filename: 'index.vue',
        content: `<template>
  <div class="main">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-tabs v-model="tabName" @tab-click="handleClick">
          {{#each $tabFields}}
          <el-tab-pane v-if="$filterTabs('{{$key}}')" label="{{$label}}" name="{{$key}}">
            <{{$key}} />
          </el-tab-pane>
          {{/each}}
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>
<script>
{{#each $tabFields}}
import {{$key}} from './components/{{$key}}.vue'
{{/each}}
import { defineComponent, ref, computed, inject, onMounted } from 'vue'
import * as localTool from '@/utils/localStorage'
import { LanguageEnum } from '@/enum/language'
import { useRoute } from 'vue-router'
import { watch } from 'vue'
export default defineComponent({
  name: 'SysLogPush',
  components: {
    {{#each $tabFields}}
    {{$key}},
    {{/each}}
  },
  props: {
  },
  emits: {},
  setup() {
    const tabName = ref('{{$showTab}}')
    // Tab跳转
    const route = useRoute()
    if (route.query && route.query.tab) {
      tabName.value = route.query.tab
    }
    watch(() => route.query.tab, () => {
      if (route.query && route.query.tab) {
        tabName.value = route.query.tab
      }
    })
    const showActionIconFlag = ref(false)
    /**
     * 获取按钮权限
     */
    const getBtnPermissions = () => {
      const showActionIcon = inject('showActionIcon')
      const pmsArray = [
      ]
      showActionIconFlag.value = showActionIcon(pmsArray)
    }
    /** 菜单切换 */
    const handleClick = (tab, event) => {
      tabName.value = tab.props.name
    }
    const init = () => {
      getBtnPermissions()
    }
    onMounted(() => {
      init()
    })
    const dialect = computed(() => {
      return localTool.getLanguageSet() === LanguageEnum.ZH
    })
    return {
      tabName,
      showActionIconFlag,
      dialect,
      init,
      getBtnPermissions,
      handleClick
    }
  }
})
</script>
<style lang="scss" scoped>
@import '@/styles/common-style.scss';
</style>
`
      }
    ]
  },
  {
    id: 'nested-demo',
    name: '多层嵌套示例',
    description: '展示条件和循环的多层嵌套能力',
    variables: [
      {
        key: 'modules',
        label: '模块列表',
        type: 'array',
        fields: [
          {
            key: 'name',
            label: '模块名称'
          },
          {
            key: 'type',
            label: '模块类型'
          },
          {
            key: 'features',
            label: '功能列表（逗号分隔）'
          },
          {
            key: 'hasPermission',
            label: '是否需要权限'
          }
        ]
      },
      {
        key: 'useTypescript',
        label: '使用TypeScript',
        type: 'text'
      },
      {
        key: 'enableI18n',
        label: '启用国际化',
        type: 'text'
      }
    ],
    subTemplates: [
      {
        filename: 'router/index.{{#if $useTypescript === "true"}}ts{{#else}}js{{/if}}',
        content: `{{#if $useTypescript === "true"}}
import { RouteRecordRaw } from 'vue-router'
{{/if}}
import Layout from '@/layout/index.vue'

{{#if $useTypescript === "true"}}
const routes: RouteRecordRaw[] = [
{{#else}}
const routes = [
{{/if}}
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {{#each $modules}}
      {{#if $item.type === "menu"}}
      {
        path: '/{{$item.name}}',
        name: '{{$item.name}}',
        component: () => import('@/views/{{$item.name}}/index.vue'),
        meta: {
          title: {{#if $enableI18n === "true"}}'route.{{$item.name}}'{{#else}}'{{$item.name}}'{{/if}},
          {{#if $item.hasPermission === "true"}}
          permissions: ['{{$item.name}}:view'],
          {{/if}}
          icon: '{{$item.name}}-icon'
        }
      },
      {{/if}}
      {{/each}}
    ]
  }
]

export default routes`
      },
      {
        filename: 'store/modules/permission.{{#if $useTypescript === "true"}}ts{{#else}}js{{/if}}',
        content: `{{#if $useTypescript === "true"}}
import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'

interface PermissionState {
  routes: RouteRecordRaw[]
  dynamicRoutes: RouteRecordRaw[]
}
{{/if}}

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    routes: [],
    dynamicRoutes: []
  }),
  
  actions: {
    {{#each $modules}}
    {{#if $item.hasPermission === "true"}}
    {{#if $first}}
    // 权限检查函数
    checkPermission(permission: string): boolean {
      const permissions = useUserStore().permissions
      return permissions.includes(permission)
    },
    {{/if}}
    
    // {{$item.name}} 模块权限
    check{{$item.name}}Permissions(): boolean {
      {{#if $item.features}}
      const features = '{{$item.features}}'.split(',')
      return features.every(feature => 
        this.checkPermission('{{$item.name}}:' + feature.trim())
      )
      {{#else}}
      return this.checkPermission('{{$item.name}}:view')
      {{/if}}
    },
    {{/if}}
    {{/each}}
    
    // 生成路由
    generateRoutes() {
      {{#if $useTypescript === "true"}}
      return new Promise<RouteRecordRaw[]>((resolve) => {
      {{#else}}
      return new Promise((resolve) => {
      {{/if}}
        const accessedRoutes = filterAsyncRoutes(asyncRoutes)
        this.routes = constantRoutes.concat(accessedRoutes)
        this.dynamicRoutes = accessedRoutes
        resolve(accessedRoutes)
      })
    }
  }
})`
      }
    ]
  }
]